import router from './router'
import store from './store'
import { validateIsNull } from '@/utils/validate'
import NProgress from 'nprogress' // 进度条插件
import 'nprogress/nprogress.css' // 进度条样式
NProgress.configure({ showSpinner: false }) // 进度条配置
const whiteList = ['/login'] 
router.beforeEach( (to, from, next) => {
  // 进度条开始
  NProgress.start()
  // 获取用户登录的token
  const token = store.getters.access_token
  // 判断当前用户是否登录
  if (token) {
    if (to.path === '/login') {
        next({ path: '/' })
    } else {
      if (store.getters.roles.length === 0) {
        store.dispatch('GetUserInfo').then(() => {
          next({ ...to, replace: true }) 
        }).catch(() => {
          store.dispatch('FedLogOut').then(() => {
            next({path: '/login'})
          })
        })
      }else{
        const value = to.path;
        const query = to.query
        const label = query.name || to.name;
        const meta = to.meta
        if(meta.isTab !== false && !validateIsNull(value) && !validateIsNull(label)){
          store.commit('ADD_TAG', {
            label: label,
            value: value,
            params: to.params,
            query: to.query,
            meta: to.meta
          });
        }
    
        next()
      }
    }
} else {
    if (whiteList.indexOf(to.path) !== -1) {
        next()
    } else {
        next(`/login`)
    }
}
})

router.afterEach(to => {
  // 结束精度条
  NProgress.done();
  let title = to.name;
  //根据当前的标签也获取label的值动态设置浏览器标题
  router.$avueRouter.setTitle(title);
})